<template>
  <div class='paper-dialog'>
    <el-dialog title="地图编辑" class="m_dialog" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form ref="form" :model="formData" :rules="rules" label-width="160px" size="small">
        <el-form-item label="地图名称:" prop="mapTitle">
          <el-input v-model="formData.mapTitle"/>
        </el-form-item>
        <el-form-item label="地图服务器地址:" prop="mapUrl">
          <el-input v-model="formData.mapUrl"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="btn_cancel">取 消</el-button>
        <el-button @click="submitForm" type="primary" class="btn_primary">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addMapInfo, updateMapInfo} from '../api/mapInfo'

export default {
  data() {
    return {
      dialogVisible: false,
      // 地图数据
      formData: {},
      // 表单验证规则
      rules: {
        mapTitle: [{required: true, message: '请输入地图名称', trigger: 'blur'}],
        mapUrl: [{required: true, message: '请输入地图服务器地址', trigger: 'blur'}, {
          pattern: /^http:\/\/|https:\/\//,
          message: '请输入正确的地址',
          trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    // 展示弹窗内容
    show(data) {
      this.dialogVisible = true
      this.resetForm()
      if (data !== undefined) {
        this.$nextTick(() => {
          this.formData = JSON.parse(JSON.stringify(data))
        })
      }
    },
    // 清空formData
    resetForm() {
      this.formData = {
        // 地图名称
        mapTitle: undefined,
        // 地图服务器地址
        mapUrl: undefined
      }
    },
    // 提交Form表单
    async submitForm() {
      try {
        const isAddOperation = this.formData.mapId === undefined
        const method = isAddOperation ? addMapInfo : updateMapInfo
        const message = isAddOperation ? '新增成功' : '修改成功'
        const response = await method(this.formData)
        if (response.code === 200) {
          this.dialogVisible = false
          this.$message.success(message)
          this.$emit('replace')
        }
      } catch (error) {
        console.log(error)
        this.$message.error('操作失败')
      }
    },
  }
}
</script>

<style scoped lang="scss">

</style>